#include <iostream>
#include <sstream>	
#include <string>
#include <stdlib.h>
#include <algorithm>
#include "Decrypter.h"

using namespace std;

DecrypterImp::DecrypterImp(EventProcessor& _controller, DistributedCounter& _dCounter)
: dCounter(_dCounter)
#ifdef DEBUG_EVPROC
: EventProcessorImp(true, "Decrypter") // comment to remove debug
#endif
{
  	controller.CopyFrom(_controller);	
  	RegisterMessageProcessor(DecryptMessage::type, &DecryptThis, 1 /*priority*/);
	EventProcessor myInterfClone;
	myInterfClone.CopyFrom(myInterface);
  	CreatedDecrypterMessage_Factory(controller,0,myInterfClone);
}

void DecrypterImp::SendDecryptedBlock(string received, int id){
	
       	transform(received.begin(),received.end(),received.begin(),::toupper);

	EventProcessor myInterfClone;
	myInterfClone.CopyFrom(myInterface);	
	
	DoneMessage_Factory(controller, id, received, myInterfClone);

}

MESSAGE_HANDLER_DEFINITION_BEGIN(DecrypterImp, DecryptThis, DecryptMessage)  
	cout<<"The message received is "<<msg.cipher<<endl;
	evProc.SendDecryptedBlock(msg.cipher, msg.id);
	//sleep(1);
	if(evProc.dCounter.Decrement(1) == 0){
		cout<<"I am the final Decrypter. killing Controller"<<endl;
		EventProcessor myInterfClone;
		myInterfClone.CopyFrom(evProc.myInterface);	
		DecryptersDoneMessage_Factory(evProc.controller, 0, myInterfClone);
		//KillEvProc(evProc.controller);
	}

	evProc.Seppuku();

MESSAGE_HANDLER_DEFINITION_END

